package com.example.springboot.service;

import com.example.springboot.entity.UserAddress;
import com.example.springboot.mapper.UserAddressMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class UserAddressService {

    private final UserAddressMapper userAddressMapper;

    public UserAddressService(UserAddressMapper userAddressMapper) {
        this.userAddressMapper = userAddressMapper;
    }

    @Transactional
    public String addUserAddress(UserAddress userAddress) {
        int count = userAddressMapper.countUserAddresses(userAddress.getUserId());
        if (count >= 5) {
            return "每个用户最多只能存储 5 个地址";
        }

        if (userAddress.getIsDefault() == 1) {
            userAddressMapper.resetDefaultAddress(userAddress.getUserId());
        }

        userAddressMapper.insertUserAddress(userAddress);
        return "地址添加成功";
    }

    public List<UserAddress> getUserAddresses(Integer userId) {
        return userAddressMapper.selectUserAddresses(userId);
    }

    @Transactional
    public String updateUserAddress(UserAddress userAddress) {
        if (userAddress.getIsDefault() == 1) {
            userAddressMapper.resetDefaultAddress(userAddress.getUserId());
        }
        userAddressMapper.updateUserAddress(userAddress);
        return "地址更新成功";
    }

    @Transactional
    public String deleteUserAddress(Integer addressId) {
        userAddressMapper.deleteUserAddress(addressId);
        return "地址删除成功";
    }
    public UserAddress getDefaultAddress(Integer userId) {
        return userAddressMapper.selectDefaultAddress(userId);
    }
}
